package com.hankol.message;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.baselibrary.MessageBus;
import com.baselibrary.activity.BaseActivity;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.router.ActivityRouter;
import com.baselibrary.utils.ARouterUtils;
import com.baselibrary.utils.GsonUtils;
import com.baselibrary.utils.PopUtils;
import com.baselibrary.utils.SpUtils;
import com.baselibrary.utils.ToastUtils;
import com.hankol.message.bean.BottomDialogBean;
import com.hankol.message.bean.ChatMsgNumBean;
import com.hankol.message.bean.ChatUserInfoBean;
import com.hankol.message.bean.FriendStateMessage;
import com.hankol.message.bean.IMUserBean;
import com.hankol.message.databinding.ActivityConversationBinding;
import com.hankol.message.fragment.MyConversationFragment;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.GenericsCallback;
import com.okhttp.sample_okhttp.JsonGenericsSerializator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imkit.IMCenter;
import io.rong.imkit.MessageInterceptor;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.ConversationClickListener;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.SightMessage;
import io.rong.message.TextMessage;
import okhttp3.Call;

/**
 * 聊天界面
 */
//消息页面（头部），下面是融云
public class ConversationActivity extends BaseActivity {
    private ActivityConversationBinding binding;
    private MyConversationFragment conversationFragment;
    //对方未关注时 已发送的消息数量
    private int alwaysSendMsgCnt = 0;
    //* 0=没关系
    //* 1=自己
    //* 2=我关注了他
    //* 3=他关注了我
    //* 4=互相关注
    private int friendState = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_conversation;
    }

    @Override
    protected void init() {
        binding = getDataBinding();
        if (!EventBus.getDefault().isRegistered(this)) {
            //如果再onCreate里注册,在账号多次被踢，登录回来的时候，onEvent接收不到消息
            EventBus.getDefault().register(this);
        }
        addActivity(this);
        initPlus();

        initListener();
        //获取页面开始时间
        SensorsDataManager.Companion.getInstance().onCreateTime();
    }

    private void initListener() {
        IMCenter.getInstance()
                .setMessageInterceptor(
                        new MessageInterceptor() {
                            @Override
                            public boolean interceptReceivedMessage(Message message, int i, boolean b, boolean b1) {
                                if (message.getContent() instanceof FriendStateMessage) {
                                    //拦截不接收好友关系提示信息
                                    return true;
                                }
                                if (message.getContent() instanceof TextMessage) {
                                    if ("4".contains(((TextMessage) message.getContent()).getExtra() + "")) {
                                        getUserInfoByUid();
                                        delTip(message);
                                    } else {
                                        if (!TextUtils.isEmpty(((TextMessage) message.getContent()).getExtra())) {
                                            //关注或者取消关注时给对方发个带扩展属性的文本消息，这里进行拦截
                                            delTip(message);
                                            return true;
                                        }
                                    }
                                }
                                return false;
                            }

                            @Override
                            public boolean interceptOnSendMessage(Message message) {
                                if (message.getContent() instanceof TextMessage) {//清除掉提示
                                    if ("4".contains(((TextMessage) message.getContent()).getExtra() + "")) {
                                        delTip(message);
                                        return false;
                                    }
                                }
                                if (!(message.getContent() instanceof FriendStateMessage) && (alwaysSendMsgCnt >= 3 || alwaysSendMsgCnt == 0) && friendState != 4) {
                                    //判断是否互相关注  //type:   0=没关系
                                    //1=自己
                                    //2=我关注了他
                                    //3=他关注了我
                                    //4=互相关注
                                    if (friendState == 2 && alwaysSendMsgCnt == 0) {//首次关注后发消息
                                        requestRecordStorageChatNum();
                                        return false;
                                    }
                                    HKIMUtils.INSTANCE.sendMessage4FriendState(message.getTargetId(), friendState);
                                    handleSensors(message, false, OptionUtils.friendState(friendState));
                                    return true;
                                }
                                if (friendState != 4) {
                                    requestRecordStorageChatNum();
                                }
                                handleSensors(message, true, OptionUtils.friendState(friendState));
                                return false;
                            }

                            @Override
                            public boolean interceptOnSentMessage(Message message) {
                                return false;
                            }

                            @Override
                            public boolean interceptOnInsertOutgoingMessage(Conversation.ConversationType type, String targetId, Message.SentStatus sentStatus, MessageContent content, long time) {
                                return false;
                            }

                            @Override
                            public boolean interceptOnInsertIncomingMessage(Conversation.ConversationType type, String targetId, String senderId, Message.ReceivedStatus receivedStatus, MessageContent content, long time) {
                                return false;
                            }
                        });
    }

    //删除提示消息
    private void delTip(Message message) {
        RongIMClient.getInstance().getHistoryMessages(Conversation.ConversationType.PRIVATE, message.getTargetId(), -1, 100, new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                ArrayList<Integer> msgids = new ArrayList<>();
                for (int i = 0; i < messages.size(); i++) {
                    if (messages.get(i).getContent() instanceof FriendStateMessage) {
                        msgids.add(messages.get(i).getMessageId());
                    }
                }
                int[] ints = new int[msgids.size()];
                for (int i = 0; i < msgids.size(); i++) {
                    ints[i] = msgids.get(i);
                }

                IMCenter.getInstance().deleteMessages(Conversation.ConversationType.PRIVATE, message.getTargetId(), ints, new RongIMClient.ResultCallback<Boolean>() {
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode e) {
                    }
                });
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
            }
        });
    }

    private void loadView() {
        if (conversationFragment == null) {
            conversationFragment = new MyConversationFragment();
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.container, conversationFragment);
            transaction.commit();

            RongIM.setConversationClickListener(new MyConversationClickListener());
            if (getIntent().getExtras() != null) {
                String title = getIntent().getExtras().getString("title");
                if (!TextUtils.isEmpty(title)) {
                    binding.tvGroupTitle.setText(title);
                }
            }
            binding.back.setOnClickListener(view -> finish());
            binding.menu.setOnClickListener(view -> {
                ArrayList<BottomDialogBean> list = new ArrayList<>();
                list.add(new BottomDialogBean("个人主页", false));
                list.add(new BottomDialogBean("举报", false));
             /*   PopUtils.INSTANCE.showBottomDialog(this, null, list, pos -> {
                    if (pos == 0) {
                        //个人主页
                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put(BaseConstant.USER_ID, String.valueOf(getIntent().getStringExtra(RouteUtils.TARGET_ID)));
                        ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap);
                    } else if (pos == 1) {
                        //举报
                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("type", 14);
                        hashMap.put("id", Integer.parseInt(getIntent().getStringExtra(RouteUtils.TARGET_ID)));
                        hashMap.put("complaintUserId", Integer.parseInt(getIntent().getStringExtra(RouteUtils.TARGET_ID)));
                        ARouterUtils.jump(ActivityRouter.ACTIVITY.REPORT, hashMap);
                    }
                }, true).show();*/
            });
        }
    }

    private void initPlus() {
            loadView();
        //showLoadingDialog();
    }


    private class MyConversationClickListener implements ConversationClickListener {
        /**
         * 当点击用户头像后执行。
         *
         * @param context          上下文。
         * @param conversationType 会话类型。
         * @param user             被点击的用户的信息。
         * @param targetId         会话 id
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
            try {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put(BaseConstant.USER_ID, String.valueOf(user.getUserId()));
                ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap);
            } catch (Exception e) {

            }
            return true;
        }

        /**
         * 当长按用户头像后执行。
         *
         * @param context          上下文。
         * @param conversationType 会话类型。
         * @param user             被点击的用户的信息。
         * @param targetId         会话 id
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {

            return false;
        }

        /**
         * 当点击消息时执行。
         *
         * @param context 上下文。
         * @param view    触发点击的 View。
         * @param message 被点击的消息的实体信息。
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageClick(Context context, View view, Message message) {
            return false;
        }

        /**
         * 当点击链接消息时执行。
         *
         * @param context 上下文。
         * @param message 被点击的消息的实体信息
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLinkClick(Context context, String s, Message message) {
            return false;
        }

        @Override
        public boolean onReadReceiptStateClick(Context context, Message message) {
            return false;
        }

        /**
         * 当长按消息时执行。
         *
         * @param context 上下文。
         * @param view    触发点击的 View。
         * @param message 被长按的消息的实体信息。
         * @return 如果用户自己处理了长按后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLongClick(Context context, View view, Message message) {
            PopupUtil.showImMesLongClick(ConversationActivity.this, (SpUtils.getInstance().getUserId() + "").equals(message.getSenderUserId()), v -> {
                if (v.getId() == R.id.tv_im_deleteMes) {
                    //删除消息
                    RongIMClient.getInstance().deleteMessages(new int[]{message.getMessageId()}, new RongIMClient.ResultCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            List<UiMessage> datas = conversationFragment.getAdapter().getData();
                            for (UiMessage data : datas) {
                                if (data.getMessageId() == message.getMessageId()) {
                                    conversationFragment.getAdapter().remove(data);
                                    conversationFragment.getAdapter().notifyDataSetChanged();
                                    break;
                                }
                            }
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
                }
            });
            return true;
        }

    }


    //判断是不是好友，获取群名字

    @Override
    protected void onResume() {
        super.onResume();
        if (Conversation.ConversationType.PRIVATE.getName().equals(getIntent().getStringExtra(RouteUtils.CONVERSATION_TYPE))) {
            //单聊
            getUserInfoByUid();
        }
        requestStorageChatNum();
    }

    private void getUserInfoByUid() {
        SendRequest.getChatUserByUid(SpUtils.getInstance().getLoadUserBean().getData().getToken(), getIntent().getStringExtra(RouteUtils.TARGET_ID), new GenericsCallback<ChatUserInfoBean>(new JsonGenericsSerializator()) {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(ChatUserInfoBean response, int id) {
                if (response != null && response.getData() != null) {
                    ChatUserInfoBean.DataBean userInfoDataBean = response.getData();
                    UserInfo userInfo = new UserInfo(String.valueOf(userInfoDataBean.getId()), TextUtils.isEmpty(userInfoDataBean.getRemark()) ? userInfoDataBean.getName() : userInfoDataBean.getRemark(), Uri.parse(userInfoDataBean.getIcon() == null ? "" : userInfoDataBean.getIcon()));
                    userInfo.setExtra(GsonUtils.toJson(new IMUserBean(userInfoDataBean.getIsFans())));
                    RongIM.getInstance().refreshUserInfoCache(userInfo);
                    binding.tvGroupTitle.setText(userInfo.getName());
                    friendState = userInfoDataBean.getFriendState();
                }
            }
        });
    }

    //和陌生人聊天数【查询】
    private void requestStorageChatNum() {
        SendRequest.reqStrangerChatNum(SpUtils.getInstance().getLoadUserBean().getData().getToken(), getIntent().getStringExtra(RouteUtils.TARGET_ID), new GenericsCallback<ChatMsgNumBean>(new JsonGenericsSerializator()) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().unregister(this);
                }
                finish();
            }

            @Override
            public void onResponse(ChatMsgNumBean response, int id) {
                alwaysSendMsgCnt = response.getData().getChatMsgNum();
            }
        });
    }

    //和陌生人聊天数【记录】
    private void requestRecordStorageChatNum() {
        SendRequest.reqRecordStrangerChatNum(SpUtils.getInstance().getLoadUserBean().getData().getToken(), getIntent().getStringExtra(RouteUtils.TARGET_ID), new GenericsCallback<ChatMsgNumBean>(new JsonGenericsSerializator()) {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(ChatMsgNumBean response, int id) {
                alwaysSendMsgCnt = response.getData().getChatMsgNum();
            }
        });
    }

    /**
     * 神策统计
     */
    private void handleSensors(Message message, Boolean isSuccess, String failReason) {
        //文字、图片、视频、
        String typeStr = "";
        if ((message.getContent() instanceof TextMessage)) {
            typeStr = "文本";
        } else if (message.getContent() instanceof ImageMessage) {
            typeStr = "图片";
        } else if (message.getContent() instanceof SightMessage) {
            typeStr = "视频";
        }
        if (getIntent().getExtras() != null) {
            SensorsDataManager.Companion.getInstance().chatWithFriends(message.getMessageId() + "", typeStr, binding.tvGroupTitle.getText().toString(), isSuccess, failReason);
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(final MessageBus messageBus) {
        if (messageBus.getCodeType().equals(MessageBus.msgId_refresh_friend_state)) {
            getUserInfoByUid();
        } else if (messageBus.getCodeType().equals(MessageBus.one_key_follow)) {
            //一键关注
            friendState = 4;
        }
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
